﻿using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Storage;
using SBlogCore.Common.Attributes;
using SBlogCore.Common.DatabaseAccessor;
using System.Reflection;

namespace SBlogCore.Common.Filters
{
    [SkipScan]
    public class UnitOfWorkFilter : IAsyncActionFilter
    {
        public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            var dbCtx = context.HttpContext.RequestServices.GetService(typeof(GlobalDbContext)) as DbContext;
            if (dbCtx != null)
            {
                using (IDbContextTransaction transaction = dbCtx.Database.BeginTransaction())
                {
                    var result = await next();
                    if (result != null) //只有Action执行成功，才能自动调用SaveChages,否则不处理
                    {
                        if (dbCtx.ChangeTracker.HasChanges()) await dbCtx.SaveChangesAsync();
                        transaction.Commit();
                    }
                    else
                    {
                        transaction.Rollback();
                    }
                }
            }
            else {
                await next();
            }
        }
    }
}
